package pers.yurwisher.rubick.common.validator;


import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.StrUtil;
import pers.yurwisher.rubick.common.validator.annotation.StringCheck;
import pers.yurwisher.rubick.common.wrapper.ValidResult;


/**
 * @author yq
 * @date 2020/08/04 10:59
 * @description 数据校验
 * @since V1.0.0
 */
public class StringCheckValidator extends AbstractCheckValidator<StringCheck, String> {

    private String fieldName;
    private boolean required;
    private String[] dataArray;
    private int maxLength;
    private int fixedLength;
    private StringCheck.StringType type;

    @Override
    public void initialize(StringCheck constraintAnnotation) {
        this.fieldName = constraintAnnotation.fieldName();
        this.required = constraintAnnotation.required();
        this.dataArray = constraintAnnotation.in();
        this.maxLength = constraintAnnotation.maxLength();
        this.fixedLength = constraintAnnotation.fixedLength();
        this.type = constraintAnnotation.type();
    }

    @Override
    public ValidResult getValidResult(String value) {
        ValidResult result = new ValidResult(fieldName);
        if (StrUtil.isEmpty(value)) {
            return result.of(!required, "必填");
        } else {
            //超出最大长度
            if (maxLength != -1 && value.length() > maxLength) {
                return result.no("最大长度", maxLength);
            }
            //不为指定长度
            if (fixedLength != -1 && value.length() != fixedLength) {
                return result.no("固定长度", fixedLength);
            }
            //不在指定范围内
            if (ArrayUtil.isNotEmpty(dataArray) && !ArrayUtil.containsAny(dataArray, value)) {
                return result.no("无效");
            }
            if (type != null || StringCheck.StringType.NONE == type) {
                boolean pass;
                switch (type) {
                    case PHONE:
                        pass = PhoneUtil.isMobile(value);
                        break;
                    case TEL:
                        pass = PhoneUtil.isTel(value);
                        break;
                    default:
                        pass = true;
                }
                return result.of(pass, "无效");
            }
            return result.pass();
        }
    }
}
